$cpi, started, timer = [], false, nil

DownstreamHook.add('cp_ds', Proc.new {|ss|
  if ss.clean_colors =~ /have to kill \* ([^\(]+) \((.+?)(?: - Dead)?\)$/
    timer = Time.now unless started
    mob_name, location, cpi_length, started = $1, $2, $cpi.length, true
    area = $db.get_first_value("SELECT num FROM Area WHERE name = ?", location)
    if area.nil?
      area_id, room_id, keywords = $db.get_first_row("SELECT a.id, r.id, m.keywords FROM Area a JOIN Room r ON r.area_id = a.id JOIN Mob m ON m.area_id = a.id WHERE r.name=? AND m.name=? LIMIT 1", location, mob_name)
      unless area_id.nil?
        area = Area[area_id]
        $cpi.insert($cpi.index {|cpi| cpi['a'] == area || !cpi.key?('a')} || $cpi.size, {'ss' => ss, 'a' => area.num, 'm' => mob_name, 'k' => keywords, 'r' => room_id})
      end
    else
      data = $db.get_first_row("SELECT m.room_id, m.keywords FROM Mob m JOIN Area a ON a.id = m.area_id WHERE m.name = ? AND a.name = ? LIMIT 1", mob_name, location)
      $cpi << {'ss' => ss, 'a' => area, 'm' => mob_name, 'k' => data[1], 'r' => data[0]}
    end
    $cpi << {'ss' => ss} if cpi_length == $cpi.length
  elsif started && ss.clean_colors =~ /You will have to level before you can go on another campaign|You may take a campaign at this level/
    DownstreamHook.remove('cp_ds')
    if started
      disp = ""
      $cpi.inject(1) {|c, v|
        disp += v['ss'].gsub(/You still have to kill \*/, "[#{cp_hunt_string(c)}]").strip
        disp += " -- #{go2_string(v['a'])} (#{go2_string(*v['r'])})\n"
        c + 1
      }
      $app.add_boxes['chat'].display_text("#{'='*80}\n#{disp}#{'='*80}\n", false)
      echo Time.now - timer
    end
  elsif !started && ss.clean_colors =~ /You may take a campaign at this level/
    start_proc(Proc.new {
      go2('cp')
      wait_while {running?('cp')}
      put('campaign request', 'd')
      wait_until {Room.current.db_id == 32611}
      go2(26151)
      put('campaign check')
    })
  end
  started ? nil : ss
})

$app.send_text('campaign check')